package azalea.mqtt.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.util.Objects;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class ClosableTabComponent extends JPanel {
    private final JLabel label;
    private final JButton closeButton;
    private final JTabbedPane tabbedPane;
    //private final int tabIndex;

    public ClosableTabComponent(JTabbedPane pane, String title, int index) {
        super(new BorderLayout());
        this.tabbedPane = pane;
        //this.tabIndex = index;
        this.setOpaque(true);
        this.setBackground(Color.white);
        label = new JLabel(title);
        //label.setBackground(Color.white);
        //label.setOpaque(true);
        closeButton = new JButton("×");
        closeButton.setFocusPainted(false);
        closeButton.setContentAreaFilled(false);
        closeButton.setBorderPainted(false);
        //closeButton.setBackground(Color.white);
        //closeButton.setOpaque(true);
        closeButton.addActionListener(e -> {
            int confirm = JOptionPane.showConfirmDialog(
                tabbedPane,
                "确认关闭此标签页？",
                "关闭标签页",
                JOptionPane.YES_NO_OPTION
            );
            if (confirm == JOptionPane.YES_OPTION) {
                //tabbedPane.removeTabAt(tabIndex);
                //tabbedPane.getComponentAt(index)
                for(int i=0;i<tabbedPane.getTabCount();++i) {
                	if(Objects.equals(title,tabbedPane.getTitleAt(i))) {
                		 tabbedPane.removeTabAt(i);
                		 GlobalCompMap.getInstance().remove(title);
                		 break;
                	}
                }
            }
        });

        add(label, BorderLayout.CENTER);
        add(closeButton, BorderLayout.EAST);
    }
}